import request from "@/services/interceptors";
import { enumValuesAtom, labelListAtom } from "@/store/enum";
import { AddEditProps, ObjectFormProps } from "@/types";
import { enumToSelectOptions, QuestionTypeEnum } from "@/utils/enums";
import { PlusOutlined } from "@ant-design/icons";
import {
  EditableProTable,
  ModalForm,
  ProColumns,
  ProFormDependency,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
} from "@ant-design/pro-components";
import { Button, Form, message } from "antd";
import { useAtomValue } from "jotai";
import { useState } from "react"; // 确保导入 useEffect

type DataSourceType = {
  optionSgin?: string;
  optionSign?: string;
};

const columns: ProColumns<DataSourceType>[] = [
  {
    title: "选项",
    dataIndex: "optionSign",
    editable: false,
  },
  {
    title: "选项值",
    dataIndex: "optionContent",
    render: (_, record, index) => {
      return index;
    },
  },
];

const AddObjectiveTopic = ({ editData, onSuccess, trigger }: AddEditProps) => {
  const { courseList } = useAtomValue(enumValuesAtom);
  const labelList = useAtomValue(labelListAtom);

  const [form] = Form.useForm<ObjectFormProps>();
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]); // 初始化为空数组

  const handleQuestionTypeChange = (value: QuestionTypeEnum) => {
    const currentOptions = form.getFieldValue("options");
    if (value === QuestionTypeEnum.选择题) {
      // 只有当 options 不存在或为空数组时才设置默认值
      if (!currentOptions || currentOptions.length === 0) {
        const letters = ["A", "B", "C", "D"];
        const defaultOptions = letters.map((letter, index) => ({
          // 使用临时唯一 ID，确保 key 的唯一性
          optionId: `new_${Date.now()}_${index}`,
          optionSign: letter,
          optionContent: "",
        }));
        form.setFieldsValue({ options: defaultOptions });
        setEditableRowKeys(defaultOptions.map((opt) => opt.optionId));
      } else {
        // 如果已有选项，则保持不变，但确保 editableKeys 同步
        setEditableRowKeys(currentOptions.map((opt) => opt.optionId));
      }
    }
  };

  const onOpenChange = async (open: boolean) => {
    if (open) {
      if (editData) {
        const res = await request.sgks.questionGetList({
          questionId: editData?.questionId,
        });
        const initialOptions = res.data.options || [];
        form.setFieldsValue({
          ...res.data,
          labelIds: res.data?.labels?.map((item) => item.labelId) ?? [],
          options: initialOptions, // 确保设置 options
        });
        // 设置编辑时的 editableKeys
        setEditableRowKeys(initialOptions.map((item) => item.optionId));
      } else {
        const res = await request.sgks.questionCodeList();
        form.resetFields(); // 清空表单
        form.setFieldsValue({
          questionCode: res.data,
        });

        setEditableRowKeys([]); // 新增时清空 keys
      }
    } else {
      // 关闭时重置 editableKeys
      setEditableRowKeys([]);
    }
  };
  return (
    <ModalForm<ObjectFormProps>
      onOpenChange={onOpenChange}
      title={editData ? "编辑客观题" : "新建客观题"}
      trigger={
        trigger || (
          <Button type="primary" icon={<PlusOutlined />}>
            新增
          </Button>
        )
      }
      labelCol={{ span: 4 }}
      layout="horizontal"
      width={640}
      form={form}
      autoFocusFirstInput
      modalProps={{
        destroyOnClose: true,
        onCancel: () => console.log("run"),
      }}
      submitTimeout={2000}
      onFinish={async (values) => {
        if (!editData && values.options) {
          values.options.map((item) => {
            delete item.optionId;
            return {
              ...item,
            };
          });
        }
        await request.sgks.questionAddOrEditCreate({
          ...values,
          questionId: editData?.questionId,
          opt: editData ? 2 : 1,
        });
        console.log(values.name);
        message.success("提交成功");
        onSuccess?.();
        return true;
      }}
    >
      <ProFormText
        rules={[{ required: true }]}
        required
        name="questionCode"
        label="题目编号"
        disabled
      />
      <ProFormSelect
        required
        name="questionType"
        label="客观题类型"
        rules={[{ required: true }]}
        options={enumToSelectOptions(QuestionTypeEnum)}
        fieldProps={{
          onChange: handleQuestionTypeChange,
        }}
      />
      <ProFormTextArea required name="questionStem" label="题干" />
      <ProFormSelect
        required
        name="courseId"
        label="所属课程"
        rules={[{ required: true }]}
        options={courseList}
      />
      <ProFormSelect
        required
        name="labelIds"
        mode="multiple"
        label="标签"
        rules={[{ required: true }]}
        options={labelList}
      />
      <ProFormTextArea name="answerAnalysis" label="答案解析" />
      <ProFormDependency name={["questionType"]}>
        {({ questionType }) => {
          if (questionType === QuestionTypeEnum.判断题) {
            return (
              <ProFormSelect
                rules={[{ required: true }]}
                name="answerTf"
                label="(判断题)答案"
                options={[
                  {
                    label: "对",
                    value: 1,
                  },
                  {
                    label: "错",
                    value: 2,
                  },
                ]}
              />
            );
          } else if (
            questionType === QuestionTypeEnum.填空题 ||
            questionType === QuestionTypeEnum.问答题
          ) {
            return (
              <ProFormTextArea
                placeholder={"多个答案使用逗号隔开"}
                rules={[{ required: true }]}
                name="answerContent"
                label="答案"
              />
            );
          } else if (questionType === QuestionTypeEnum.选择题) {
            return (
              <>
                <EditableProTable<DataSourceType>
                  name="options"
                  rowKey="optionId"
                  toolBarRender={false}
                  controlled
                  columns={columns}
                  formItemProps={{
                    label: "选项编辑",
                    required: true,
                    rules: [
                      {
                        validator: async (_, value) => {
                          if (value.length < 1) {
                            throw new Error("请至少添加一个选项");
                          }

                          if (value.length > 4) {
                            throw new Error("最多可以设置四个选项");
                          }
                        },
                      },
                    ],
                  }}
                  recordCreatorProps={false}
                  editable={{
                    type: "multiple",
                    editableKeys,
                    // onChange 同步更新 editableKeys 和 form value
                    onChange: (keys, rows) => {
                      setEditableRowKeys(keys);
                      form.setFieldsValue({ options: rows }); // 确保 form 值也更新
                    },
                    actionRender: () => {
                      return [];
                    },
                  }}
                />
                <ProFormSelect
                  rules={[{ required: true }]}
                  name="answerChoice"
                  label="(选择题)答案"
                  options={[
                    {
                      label: "A",
                      value: "A",
                    },
                    {
                      label: "B",
                      value: "B",
                    },
                    {
                      label: "C",
                      value: "C",
                    },
                    {
                      label: "D",
                      value: "D",
                    },
                  ]}
                />
              </>
            );
          }
          return null; // 确保在其他情况下返回 null
        }}
      </ProFormDependency>
    </ModalForm>
  );
};

export default AddObjectiveTopic;
